package com.yu.thread5;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaolongyu on 15/3/19.
 */
public class CriticalSection {

    public static void testApproaches(PairManager pm1, PairManager pm2){
        ExecutorService exec = Executors.newCachedThreadPool();
        PairManipulator
                pman1 = new PairManipulator(pm1),
                pman2 = new PairManipulator(pm2);
        PairChecker
                pcheck1 = new PairChecker(pm1),
                pcheck2 = new PairChecker(pm2);

        exec.execute(pman1);
        exec.execute(pman2);
        exec.execute(pcheck1);
        exec.execute(pcheck2);

        try {
            System.out.println("---->" + System.currentTimeMillis());
            TimeUnit.MILLISECONDS.sleep(5000);
            System.out.println("---->end:" + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("pman1:" + pman1 + "\npman2:" + pman2);
        System.exit(0);

    }

    public static void main(String[] args) {
        PairManager pm1 = new PairManager1();
        PairManager pm2 = new PairManager2();
        testApproaches(pm1, pm2);
    }

}

class Pair{
    private int x, y;
    public Pair(int x, int y){
        this.x = x;
        this.y = y;
    }

    public Pair(){
        this(0, 0);
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }

    public void incrementX(){
        x ++;
    }
    public void incrementY(){
        y ++;
    }
    public String toString(){
        return "x:" + x + " y:" + y;
    }
    public void checkState(){
        if(x != y){
            throw new PairValuesNotEqualException();
        }
    }

    public class PairValuesNotEqualException extends RuntimeException {
        private static final long serialVersionUID = 7479759716709783123L;

        public PairValuesNotEqualException(){
            super("Pair values not equal:" + Pair.this);
        }
    }
}
